using System;
using System.Linq;

namespace Voodoo.Sauce.Internal.Analytics
{
	internal class ConversionEventsManager
	{
		private DateTime? _expirationDateTime;

		private ConversionEventsSettings _eventsSettings;

		private static ConversionEventsManager instance;

		internal static ConversionEventsManager Instance => instance ?? (instance = new ConversionEventsManager());

		internal void Initialize(ConversionEventsSettings settings)
		{
			Initialize(settings, AnalyticsStorageHelper.Instance.GetFirstAppLaunchDate());
		}

		internal void Initialize(ConversionEventsSettings eventsSettings, DateTime? installDate)
		{
			if (eventsSettings != null && eventsSettings.IsEnabled() && eventsSettings.HasValidExpirationDate())
			{
				_eventsSettings = eventsSettings;
				_expirationDateTime = installDate?.Date.AddDays(eventsSettings.DaysUntilExpiration);
			}
			else
			{
				_eventsSettings = null;
				_expirationDateTime = null;
			}
		}

		internal ConversionEventInfo GetInterstitialConversionEvent(AdClosedEventAnalyticsInfo adEvent)
		{
			return GetConversionAdEvent(adEvent, ConversionEventName.FS);
		}

		internal ConversionEventInfo GetRewardedVideoConversionEvent(AdClosedEventAnalyticsInfo adEvent)
		{
			return GetConversionAdEvent(adEvent, ConversionEventName.RV);
		}

		private ConversionEventInfo GetConversionAdEvent(AdClosedEventAnalyticsInfo adEvent, ConversionEventName conversionEventName)
		{
			if (!IsEventsNotExpired())
			{
				return null;
			}
			return _eventsSettings?.AdEvents?.FirstOrDefault((ConversionAdEventInfo eventInfo) => eventInfo.Name == conversionEventName && eventInfo.TargetNumberAdsWatched == adEvent.AdWatchedCount);
		}

		private bool IsEventsNotExpired()
		{
			if (_eventsSettings != null && _expirationDateTime.HasValue)
			{
				DateTime utcNow = DateTime.UtcNow;
				DateTime? expirationDateTime = _expirationDateTime;
				return utcNow < expirationDateTime;
			}
			return false;
		}
	}
}
